// src/utils/buttonActions.ts
import { message } from 'antd';
import {createNum, cleanNum, saveScratchShelf, batchSubmit} from '@/services/prefiling/onlineCollecting';
import { useNavigate } from 'umi';

type ActionHandler = (params: {
  modelType: string;
  selectedRows: React.Key[];
  currentType?: { typeCode: string; arrangeDimension: 'FILE' | 'ROLL'; fullId: string, name: string, fullNo: string };
  menuId: string;
  fileState: string;
}) => void | Promise<void>;

type RefreshHandler = () => void;

let globalLoading = false;
let loadingChangeCallback: (loading: boolean) => void = () => { };
let globalOpenTab: Function | null = null;
// 初始化函数
export const initButtonActions = (openTabFn: Function) => {
  globalOpenTab = openTabFn;
};
//按钮方法定义
const baseActions: Record<string, ActionHandler> = {

  //新增
  prefiling_oc_add: ({ currentType, fileState, menuId, modelType }) => {
    if (!currentType) {
      message.warning('缺少必要的类型参数');
      return;
    }
    // 确保每次调用生成唯一 key
    const tabKey = `onlineCollecting-${currentType.typeCode}`;

    if (window.openGlobalTab) {
      window.openGlobalTab(
        tabKey,
        `${currentType.name}新增`,
        '/prefiling/onlineCollecting/add',
        {
          typeCode: currentType.typeCode,
          fileState,
          arrangeDimension: currentType.arrangeDimension,
          fullId: currentType.fullId,
          pageLink: menuId,
          modelType,
          fullNo: currentType.fullNo,
        }
      );
    }

  },
  //生成档号
  prefiling_oc_scdh: async ({ selectedRows, currentType, fileState }) => {
    if (selectedRows.length) {
      let ids = selectedRows.toString();
      const response = await createNum({
        ids: ids,
        typeCode: currentType?.typeCode || '',
        fullId: currentType?.fullId || '',
        fileType: currentType?.arrangeDimension || 'FILE',
        fileState: fileState
      });

      if (response.code === 0) {
        message.success('生成档号成功');
        ActionDispatcher.triggerRefresh(); // 执行成功后触发刷新
      } else {
        message.error(response.msg)
      }
    } else {
      message.warning('请先选择要生成档号的记录');
    }
  },
  //清除档号
  prefiling_oc_qcdh: async ({ selectedRows, currentType, fileState }) => {
    if (selectedRows.length) {
      let ids = selectedRows.toString();
      const response = await cleanNum({
        ids: ids,
        typeCode: currentType?.typeCode || '',
        fullId: currentType?.fullId || '',
        fileType: currentType?.arrangeDimension || 'FILE',
        fileState: fileState
      });

      if (response.code === 0) {
        message.success('清除档号成功');
        ActionDispatcher.triggerRefresh();
      } else {
        message.error(response.msg)
      }
    } else {
      message.warning('请先选择要清除档号的记录');
    }
  },
  //移交申请
  prefiling_oc_yjsq: async ({ selectedRows, currentType, fileState }) => {

  },
  //附件上传
  prefiling_oc_upload: async ({ selectedRows, currentType, fileState }) => {

  },
  //归入整编
  prefiling_oc_b_add: async ({ selectedRows, currentType, fileState }) => {
    if (selectedRows.length) {
      let ids = selectedRows.toString();
      const response = await batchSubmit({
        fileList: JSON.stringify(selectedRows.map(item => ({id:item}))),
        typeCode: currentType?.typeCode || '',
        fullId: currentType?.fullId || '',
        arrangeDimension: currentType?.arrangeDimension || 'FILE',
        fileState: fileState
      });

      if (response.code === 0) {
        message.success('提交成功');
        ActionDispatcher.triggerRefresh(); // 执行成功后触发刷新
      } else {
        message.error(response.msg)
      }
    } else {
      message.warning('请先选择要归入整编的记录');
    }
  },
  //加入暂存架
  prefiling_oc_jrzcj: async ({ selectedRows, currentType, fileState }) => {
    console.log({ selectedRows, currentType, fileState });

    if (selectedRows.length) {
      let ids = selectedRows.toString();
      const params = {
        cfmsCollectInfo: JSON.stringify(selectedRows.map((item) => ({
          ...currentType,
          state: fileState,
          fileId: item,
        })))
      }
      console.log('params=',params);
      
      const response = await saveScratchShelf(params);

      if (response.code === 0) {
        message.success('操作成功');
        ActionDispatcher.triggerRefresh();
      } else {
        message.error(response.msg)
      }
    } else {
      message.warning('请先选择要加入暂存架的记录');
    }
  },
  //移库
  prefiling_oc_yk: async ({ selectedRows, currentType, fileState }) => {

  },
  //综合排序
  prefiling_oc_zhpx: async ({ selectedRows, currentType, fileState }) => {

  },
  //导出
  prefiling_oc_export: async ({ selectedRows, currentType, fileState }) => {

  },
  //查找重复档号
  prefiling_oc_czcfdh: async ({ selectedRows, currentType, fileState }) => {

  },
  //材料扫描
  prefiling_oc_clsm: async ({ selectedRows, currentType, fileState }) => {

  },
  //条目导入
  prefiling_oc_import: async ({ selectedRows, currentType, fileState }) => {

  },
  //批量修改
  prefiling_oc_b_edit: async ({ selectedRows, currentType, fileState }) => {

  },
  //数据查重
  prefiling_oc_b_check: async ({ selectedRows, currentType, fileState }) => {

  },
  //复制新增
  prefiling_oc_copy_add: async ({ selectedRows, currentType, fileState }) => {

  },
  //批量删除
  prefiling_oc_b_del: async ({ selectedRows, currentType, fileState }) => {

  },
  //批量删除附件
  prefiling_oc_del_file: async ({ selectedRows, currentType, fileState }) => {

  },
  //移交记录
  prefiling_oc_yjjl: async ({ selectedRows, currentType, fileState }) => {

  },
  //卷内文件新增
  prefiling_oc_jnwjxz: async ({ selectedRows, currentType, fileState }) => {

  },
  //拆卷
  prefiling_oc_unreel: async ({ selectedRows, currentType, fileState }) => {

  },
  //自动组卷
  prefiling_oc_zdzj: async ({ selectedRows, currentType, fileState }) => {

  },
  //合并
  prefiling_oc_combine: async ({ selectedRows, currentType, fileState }) => {

  },
  //迁移
  prefiling_oc_qy: async ({ selectedRows, currentType, fileState }) => {

  },
  //查看全部卷内文件
  prefiling_oc_ckqbjnwj: async ({ selectedRows, currentType, fileState }) => {

  },
  //迁出
  prefiling_oc_qc: async ({ selectedRows, currentType, fileState }) => {

  },
  //组卷
  prefiling_oc_zj: async ({ selectedRows, currentType, fileState }) => {

  },
  //迁入
  prefiling_oc_qr: async ({ selectedRows, currentType, fileState }) => {

  },
  //批量下载附件
  prefiling_oc_blxzfj: async ({ selectedRows, currentType, fileState }) => {

  },
  //导入记录
  prefiling_ac_drjl: async ({ selectedRows, currentType, fileState }) => {

  },
  //关联档案
  prefiling_oc_relate: async ({ selectedRows, currentType, fileState }) => {

  },
  //查看关联档案
  prefiling_oc_scanRelate: async ({ selectedRows, currentType, fileState }) => {

  },
  //锁定
  prefiling_oc_lock: async ({ selectedRows, currentType, fileState }) => {

  },
  //解锁锁定
  prefiling_oc_unlock: async ({ selectedRows, currentType, fileState }) => {

  },
  //组件
  prefiling_oc_recoling: async ({ selectedRows, currentType, fileState }) => {

  },
};

let customActions: Record<string, ActionHandler> = {};
let refreshCallback: RefreshHandler | null = null;

export const ActionDispatcher = {
  execute: async (permission: string, params: any) => {
    if (globalLoading) return;

    globalLoading = true;
    loadingChangeCallback(true);
    try {
      const handler = customActions[permission] || baseActions[permission];
      await handler?.(params);
    } finally {
      globalLoading = false;
      loadingChangeCallback(false);
    }
  },
  setLoadingHandler: (callback: (loading: boolean) => void) => {
    loadingChangeCallback = callback;
  },

  getLoadingState: () => globalLoading,
  setRefreshHandler: (handler: RefreshHandler) => {
    refreshCallback = handler;
  },

  triggerRefresh: () => {
    refreshCallback?.();
  },

  clearRefreshHandler: () => {
    refreshCallback = null;
  },

  register: (actions: Record<string, ActionHandler>) => {
    customActions = { ...customActions, ...actions };
  },

  reset: () => {
    customActions = {};
  }
};